<?php
namespace app\api\controller;
use app\common\controller\Api;

class Shiku extends Api
{
    
    public $midPlatform = "";//平台商户号
	public $aesKey = "";//aes_key
	public $md5Key = "";//md5_key
	public $api_url = "";//api地址

	public $iv = '0102030405060708';


	/**
	 * 初始化
	 * @param array $config
	 */
	public function __construct($config = [])
	{
		$this->aesKey      = $config['aesKey'];
		$this->md5Key      = $config['md5Key'];
		$this->midPlatform = $config['midPlatform'];
		$this->api_url     = $config['api_url'];
    }
    
    /**
	 * 执行请求
	 * @param $data
	 * @return bool|mixed
	 */
	public function execute($data)
	{

		$json_data = json_encode($data);//转为json

		$post_data['sign']        = md5($json_data . $this->md5Key);//MD5签名
		$post_data['data']        = $this->encrypt($json_data);//AES加密
		$post_data['midPlatform'] = $this->midPlatform;
		$post_data['version']     = 'V1.0';

		$res = $this->post($this->api_url, $post_data);
		$res = json_decode($res, true);

		$res['data'] = $this->decrypt($res['data']);//AES解密
		//验证
		if (!$res['data']) {
			//echo '未返回有效数据';
			return false;
		}

		if ($res['sign'] <> md5($res['data'] . $this->md5Key)) {
			//echo '验签失败';
			return false;
		}

		$res['data'] = json_decode($res['data'], true);
		return $res['data'];

	}

	/**
	 * 提交数据
	 * @param $url
	 * @param array $post
	 * @return mixed
	 */
	private function post($url, $post = array())
	{
		$post_string = json_encode($post);
		$ch          = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json;charset=utf-8'));
		curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
		$data = curl_exec($ch);
		curl_close($ch);
		return $data;
	}


	/**
	 * AES加密
	 * @param $input
	 * @return string
	 */
	private function encrypt($input)
	{
		$data = openssl_encrypt($input, 'AES-128-CBC', $this->aesKey, OPENSSL_RAW_DATA, $this->iv);
		$data = bin2hex($data);
		return $data;
	}


	/**
	 * AES解密
	 * @param $sStr
	 * @return string
	 */
	private function decrypt($sStr)
	{
		$decrypted = openssl_decrypt(hex2bin($sStr), 'AES-128-CBC', $this->aesKey, OPENSSL_RAW_DATA, $this->iv);
		return $decrypted;
	}
}